from dao import Dao
from model.address import Address
from bson.dbref import DBRef

class AddressDao(Dao):
    def __init__(self):
        Dao.__init__(self, Address)
        self.collection = 'addresses'
        
    def insert(self, address):
        """Save the object to collection
        Arguments:
            address --- The Address Model object
        """
        if isinstance(address, Address):
            # Insert except ID field, because ID will be automatically generated
            _dict = {}
            _dict['unit'] = address.unit;
            _dict['street_no'] = address.street_no;
            _dict['street_name'] = address.street_name;
            _dict['postcode'] = address.postcode;
            _dict['city'] = DBRef('cities', address.city._id );
            
            return self.db.insert(self.collection, _dict)
        return None   

    def save(self, model):
        """Updates an existing document or inserts a new document, depending on its document parameter.
        Arguments:
            model --- The Model object with id, if model is a dict type, the dbref field must be DBRef type
        Return:
            The '_id' value of to_save or [None] if manipulate is False and to_save has no _id field.
        """
        # The ID field must exist
        if isinstance(model, dict):
            return self.db.save(self.collection, model)
        else:
            _dict = model.__dict__
            if _dict is not None:
                _dict['city'] = DBRef('cities', model.city._id)
                return self.db.save(self.collection, _dict)
            else:
                return None

        
    def find_one(self, query):
        """
        Arguments:
            query --- The dict type
        Return:
            Raises TypeError if any of the arguments are of improper type. 
            Returns an instance of Cursor corresponding to this query.
        """
        _dict = self.db.find_one(self.collection, query)
        if _dict is not None:
            _dbref = _dict['city']
            _dict['city'] = self.db.find_one('cities', {'_id':_dbref.id})
            return self.ModelClass(_dict)
        else:
            return None
    
    def find(self, query={}):
        """
        Arguments:
            query --- The dict type
        Return:
            Raises TypeError if any of the arguments are of improper type. 
            Returns an instance of Cursor corresponding to this query.
        """
        cursor = self.db.find(self.collection, query=query)
        rets = []
        for _dict in cursor:
            _dict['city'] = self.db.find_one('cities', {'_id':_dict['city']._id})
            rets.append(_dict)
        return rets
